import request from "../../utils/request"
let isSend=null
Page({
    /**
     * 页面的初始数据
     */
    data: {
        placeholderContent:'',//placeholder默认内容
        hotList:[],
        searchContent:'',//用户获取的表单项数据内容
        searchList:[],//搜索到的数据
        historyList:[],//搜索历史记录
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        this.getInitData()
        /* 获取历史记录 */
        this.getHistoryList()
    },
    async getInitData(){
        let placeholderData=await request('/search/default')
        let hotListData=await request('/search/hot/detail')
        this.setData({
            placeholderContent:placeholderData.data.showKeyword,
            hotList:hotListData.data
        })
    },
    handleInputChange(event){
        this.setData({
            searchContent:event.detail.value.trim()
        }) 
        clearTimeout(isSend)
        isSend=setTimeout(() => {
            this.getSearchList()
        }, 300);
    },
    async getSearchList(){
        let {searchContent,historyList}=this.data
        if(!searchContent){
            this.setData({
                searchContent:[]
            })
            return
        }
        let searchListData = await request('/search', {keywords: searchContent, limit: 10});
        this.setData({
        searchList: searchListData.result.songs
        })

        // 将搜索的关键字添加到搜索历史记录中
        if(historyList.indexOf(searchContent)!==-1){
            historyList.splice(historyList.indexOf(searchContent),1)
        }
        historyList.unshift(searchContent)
        this.setData({
            historyList
        })
        wx.setStorageSync('historyList', historyList)  
    },
    getHistoryList(){
        let history=wx.getStorageSync('historyList')
        if(history){
            this.setData({
                historyList:history
            })
        }

    },
    /* 删除所有历史记录 */
    clearHistoryList(){
        this.setData({
            historyList:[]
        })
        wx.setStorageSync('historyList', '')
    },
    /* 删除输入框文字 */
    clear(){
        this.setData({
            searchContent: '',
            searchList: []
          })
    },
    
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {

    }
})